package org.jasig.cas.authentication.handler;
/**
*	Copyright © 2012 - 2016 优必选科技  Ubtrobot Tech. All Rights Reserved 
*/

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.jasig.cas.authentication.handler.PasswordEncoder;
/**
 * 功能说明：
 * 
 * MD5PasswordEncoder.java
 * 
 * Original Author: deane.jia,2016年11月9日 上午11:19:12
 * 
 * Copyright (C)2012-2016 深圳优必选科技 All rights reserved.
 */
public class MyMD5PasswordEncoder implements PasswordEncoder{

	private int bit = 32;
	
	public MyMD5PasswordEncoder(String bit) {
		this.bit = Integer.valueOf(bit);
	}

	public String encode(String password) {
		try {
			String regex = "^(?![0-9]+$)(?![a-z]+$)[0-9a-z]{32,32}$";
			//判断是否MD5 32位加密，定义为：小写字母，同时长度为32位
			if(!password.matches(regex)){
				MessageDigest md = MessageDigest.getInstance("MD5");
	            md.update(password.getBytes());
	            byte b[] = md.digest();
	            int i;
	            StringBuffer buf = new StringBuffer("");
	            for (int offset = 0; offset < b.length; offset++) {
	                i = b[offset];
	                if (i < 0)
	                    i += 256;
	                if (i < 16)
	                    buf.append("0");
	                buf.append(Integer.toHexString(i));
	            }
	            if (bit == 32) {
	            	System.out.println("password is ========>" + buf.toString());
	                return buf.toString();
	            } else {
	                return buf.toString().substring(8, 24);
	            }
			}else{
				return password;
			}
            
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
	}
	
	public static void main(String[] args) {
		MyMD5PasswordEncoder mdsLitte = new MyMD5PasswordEncoder("32");
		System.out.println(mdsLitte.encode("123456"));
		//
		String value="e10adc3949ba59abbe56e105710f883e";
		String regex = "^(?![0-9]+$)(?![a-z]+$)[0-9a-z]{32,32}$";
		if(value.matches(regex)){
			System.out.println("match");
		}else{
			System.out.println("unmatch");
		}
	}

}
